#!/usr/bin/python

from string import Template


def generate_validation(disabled_contexts, directive):
    """
    Generate the code for initial validation
    """

    str = """
    def validate(self):
    """

    check = Template( """
        if self.parent.directive == "$type":
            raise Exception, 'Directive $d is not allowed in a $context context'
            """)

    if disabled_contexts == "":
        str += """
        pass
               """
        return str

    for d in disabled_contexts:
        if( d == "s" ):
            str += check.substitute(type="ConfigNode", d=directive, context="Server")
        elif(d == "v"):
            str += check.substitute(type="VirtualHost", d=directive, context="VirtualHost")
        elif(d == "d"):
            str += check.substitute(type="Directory", d=directive, context="Directory")
        elif(d == "h"):
            #I'll need to think about this... for now we'll do nothing
            str += """
        pass
                   """
    return str

def reverse_contexts(contexts):
    """
    Take a string of allowed contexts and return a string of contexts that are not allowed
    """
    d_contexts = "svdh"
    for c in contexts:
        d_contexts = d_contexts.replace(c, '')
    return d_contexts


f = open("directives2.txt", "r")

template = Template(
"""# $name.py
# ConfigNode for $name directives
#

from conf import ConfigNode

class $name(ConfigNode.ConfigNode):
    def __init__(self, args):
        ConfigNode.ConfigNode.__init__(self)
        self.directive = "$name"
        self.args = args
        self.comment = ""
        self.children = [] 

 """)


scoped_template = Template(
"""# $name.py
# ConfigNode for $name directives
#

from conf import ConfigNode

class $name(ConfigNode.ConfigNode):
    def __init__(self, args):
        ConfigNode.ConfigNode.__init__(self)
        self.directive = "$name"
        self.args = args
        self.comment = ""
        self.children = []
        self.is_scoped = True

    def __repr__(self):
        return "<" + self.directive + " " + ' '.join(self.args) + ">"

    def __str__(self):
        return "<" + self.directive + " " + ' '.join(self.args) + ">"
   
 """)

import shutil, os.path

if not os.path.exists( "directives" ):
    os.mkdir( "directives" )

for l in f:
    l = l[0:len(l)-1] #Strip out endlines
    lst = l.split()
    fout = open( "directives/" + lst[0].lstrip("< ")+".py", "w")
    if lst[0].startswith("<"):
        fout.write( scoped_template.substitute(name=lst[0].lstrip("< ")) )
    else:
        fout.write( template.substitute(name=lst[0]) )
    fout.write( generate_validation( reverse_contexts(lst[1]), lst[0]))
    fout.close()
    
shutil.copy( "__init__.py_directives", "directives/__init__.py" )
shutil.copy( "Include.py__bak", "directives/Include.py" )
